package com.hua.ui;

import com.hua.Dao.Mysql;
import com.hua.Service.funtion;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class PermissManage extends JFrame {
	private Connection conn; // 数据库连接
	private JTable table; // 表格组件，用于显示数据
	private JButton submitButton; // 提交按钮

	public PermissManage() throws SQLException {
		conn = Mysql.GetConn(); // 获取数据库连接
		setupTable(); // 设置表格
		setTitle("管理员登录!"); // 设置窗口标题
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗口关闭行为
		setSize(1500, 300); // 设置窗口大小

		submitButton = new JButton("提交修改"); // 创建提交按钮
		submitButton.addActionListener(new ActionListener() { // 为提交按钮添加动作监听器
			@Override
			public void actionPerformed(ActionEvent e) {
				submitChanges(); // 当按钮被点击时，提交更改
			}
		});
		add(submitButton, BorderLayout.SOUTH); // 将提交按钮添加到窗口的南部（底部）

		setVisible(true); // 使窗口可见
		table.setFont(new Font("Serif", Font.PLAIN, 20));
		table.setRowHeight(30);
	}

	private void setupTable() throws SQLException {
		// SQL查询语句，用于获取用户和权限数据
		String sql = ("SELECT user_id,`name`,account,password,sign,img,login,`write`,`delete`,ai,`rename`,upload,download,`share`\n"
				+ "FROM Permiss JOIN Users \n" + "ON Permiss.user_id = Users.id");
		PreparedStatement query = conn.prepareStatement(sql); // 准备SQL查询
		ResultSet rs = query.executeQuery(); // 执行查询，获取结果集
		DefaultTableModel model = new DefaultTableModel(); // 创建表格模型
		ResultSetMetaData rsmd = rs.getMetaData(); // 获取结果集的元数据
		int columnCount = rsmd.getColumnCount(); // 获取列数

		for (int i = 1; i <= columnCount; i++) {
			model.addColumn(rsmd.getColumnName(i)); // 为表格模型添加列
		}
		while (rs.next()) { // 遍历结果集
			Object[] row = new Object[columnCount]; 
			for (int i = 1; i <= columnCount; i++) {
				row[i - 1] = rs.getObject(i); // 获取列的值，存入数组
			}
			model.addRow(row); // 将数组添加为表格模型的一行
		}
		table = new JTable(model); // 使用表格模型创建表格
		JScrollPane scrollPane = new JScrollPane(table); // 创建滚动面板，包含表格
		add(scrollPane, BorderLayout.CENTER); // 将滚动面板添加到窗口的中心
	}

	private void submitChanges() {
		DefaultTableModel model = (DefaultTableModel) table.getModel(); // 获取表格模型
		int i = table.getSelectedRow(); // 获取选中的行
		if (i >= 0) { // 如果有选中的行
			try {
				boolean flag = updatePermissions(i, model); // 更新权限
				if (flag) {
					// 显示成功消息
					JOptionPane.showMessageDialog(this, "用户 " + model.getValueAt(i, 1) + " 的权限已成功更新", "成功",
							JOptionPane.INFORMATION_MESSAGE);
				}
			} catch (SQLException e) {
				// 显示错误消息
				JOptionPane.showMessageDialog(this, "更新用户 " + model.getValueAt(i, 0) + " 的权限时出错", "错误",
						JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}
		} else {
			JOptionPane.showMessageDialog(this, "请先选择一个用户", "错误", JOptionPane.ERROR_MESSAGE);
		}
	}

	private boolean updatePermissions(int rowIndex, DefaultTableModel model) throws SQLException {
		String[] permissions = new String[14]; // 创建一个数组，用于存储权限
		boolean flag = true;
		for (int j = 1; j < permissions.length; j++) {
			String value = model.getValueAt(rowIndex, j).toString();
			if (j >= 6 && j <= 13) { 
				if (value.equals("true") || value.equals("false")) {
					permissions[j] = value.equals("true") ? "1" : "0";
				} else {
					JOptionPane.showMessageDialog(this, "请输入true 或者 false", "错误", JOptionPane.ERROR_MESSAGE);
					flag = false; 
					break; 
				}
			}  else {
				System.out.println("添加其他列");
				permissions[j] = value; // 对于其他列，直接保存用户输入的值
			}
		}

		// SQL查询语句，用于获取数据库中的user_id
		Object value = model.getValueAt(rowIndex, 0);
		if (value instanceof String) {
			JOptionPane.showMessageDialog(this, "user_id不能被修改", "错误", JOptionPane.ERROR_MESSAGE);
			throw new SQLException("user_id不能被修改");
		} else if (value instanceof Integer) {
			Integer userIdTb = (Integer) value;

			// SQL查询语句，用于获取数据库中的user_id
			String sqlQuery = "SELECT id FROM Users WHERE id = ?";
			PreparedStatement query = conn.prepareStatement(sqlQuery);
			query.setInt(1, userIdTb);
			ResultSet rs = query.executeQuery();
			if (rs.next()) {
				Integer userIdDb = rs.getInt("id");
				if (!userIdTb.equals(userIdDb)) {
					JOptionPane.showMessageDialog(this, "user_id不能被修改", "错误", JOptionPane.ERROR_MESSAGE);
					throw new SQLException("user_id不能被修改");
				}
			}
		}

		// SQL更新语句，用于更新Users表
		String sql1 = "UPDATE Users SET name = ?, account = ?, password = ?, sign = ?, img = ? WHERE id = ?";
		PreparedStatement update1 = conn.prepareStatement(sql1); // 准备SQL更新
		update1.setString(1, (String) model.getValueAt(rowIndex, 1));
		update1.setString(2, (String) model.getValueAt(rowIndex, 2));
		update1.setString(3, (String) model.getValueAt(rowIndex, 3));
		update1.setString(4, (String) model.getValueAt(rowIndex, 4));
		update1.setString(5, (String) model.getValueAt(rowIndex, 5));
		update1.setInt(6, (Integer) model.getValueAt(rowIndex, 0));
		int count1 = update1.executeUpdate(); // 执行更新
		System.out.println("Users受影响的行数: " + count1);

		// SQL更新语句，用于更新Permiss表
		String sql2 = "UPDATE Permiss SET `login` = ?, `write` = ?, `delete` = ?, "
				+ "`ai` = ?, `rename` = ?, `upload` = ?, `download` = ?, `share` = ? WHERE `user_id` = ?";
		PreparedStatement update2 = conn.prepareStatement(sql2); // 准备SQL更新
		for (int k = 6; k < 14; k++) { 
			
			update2.setString(k - 5, permissions[k]);
		}
		update2.setInt(9, (Integer) model.getValueAt(rowIndex, 0)); // 设置最后一个参数（Permiss.user_id）
		int count2 = update2.executeUpdate(); // 执行更新

		System.out.println("Permiss受影响的行数: " + count2);
		System.out.println("User ID: " + model.getValueAt(rowIndex, 0)); // 打印user_id

		return flag;
	}

	public static void main(String[] args) {
		try {
			new PermissManage(); // 创建并显示窗口
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
